<?php

namespace app\model;

use think\Model;

class Admin extends Model
{
    //
    /**
     * 加密用户输入的密码
     * @param $str     需要加密的密码
     * @return string  加密过的密码
     */
    public function passEncryption( $str )
    {
        return substr( md5( $str ), 10, 30 );
    }

    /**
     * 登录验证
     * @param $info
     * @return array
     */
    public function adminLogin( $info )
    {

        if ( $info[ 'username' ] && $info[ 'token' ] && $info[ 'password' ] ) {

            $pw = $this->passEncryption( $info[ 'password' ] );
            $token = $this->passEncryption( $info[ 'token' ] );

            $where = [ 'name' => $info[ 'username' ], 'pw' => $pw, 'token' => $token ];

            $re = $this->where( $where )->find();

            if ( $re ) {

                $return = [ 'status' => true, 'info' => $re ];

                db( 'log' )->insert( [ 'cd' => time(), 'content' => '管理员：' . $info[ 'username' ] . '登录后台' ] );

            } elseif ( $re[ 'status' == 0 ] ) {

                $return = [ 'status' => false, 'info' => '账户已被封禁' ];

            } else {

                $return = [ 'status' => false, 'info' => '用户名密码验证码错' ];

            }

        } else {

            $return = [ 'status' => false, 'info' => '参数错误' ];

        }

        return $return;

    }

    /**
     * 新增管理员
     * @param $info
     * @return array
     */
    public function addAdmin( $info )
    {
        if ( $info[ 'username' ] && $info[ 'token' ] && $info[ 'password' ] && $info[ 'email' ] ) {

            $insert = [ 'name' => $info[ 'username' ], 'pw' => $this->passEncryption( $info[ 'password' ] ), 'token' => $this->passEncryption( $info[ 'token' ] ), 'email' => $info[ 'email' ], 'status' => 1 ];

            $re = $this->save($insert);

            if($re){

                $return = ['status'=>true];

            }else{

                $return = [ 'status' => false, 'info' => '数据写入错误' ];

            }

        } else {

            $return = [ 'status' => false, 'info' => '参数错误' ];

        }

        return $return;

    }

}
